﻿/*
  DISCLAIMER:
THIS CODE IS SAMPLE CODE. THESE SAMPLES ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
MICROSOFT FURTHER DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR OF FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK ARISING OUT OF THE USE OR PERFORMANCE OF THE SAMPLES REMAINS WITH YOU. IN NO EVENT SHALL
MICROSOFT OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THE
SAMPLES, EVEN IF MICROSOFT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION
OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU.
 * */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Reflection;

namespace WebDAV_Test_Application
{
    public partial class FormMain : Form
    {
        private FormListener _httpListener = null;
        private List<string[]> _RequestHeaders = new List<string[]>();
        private ClassLogger _logger = null;

        public FormMain()
        {
            InitializeComponent();
            ReadSettingsFromRegistry();
            _logger=new ClassLogger(Path.GetDirectoryName(Application.ExecutablePath) + "\\WebDAV Log.txt");
        }

        ~FormMain()
        {
            _logger = null;
            GC.Collect();
        }

        public FormListener HTTPListener
        {
            get
            {
                if (_httpListener == null)
                {
                    _httpListener = new FormListener();
                    _httpListener.Show(this);
                }
                return _httpListener;
            }
        }

        private ICredentials CurrentCredentials
        {
            get
            {
                ICredentials oCredential;
                if (checkBoxUseDefault.Checked)
                {
                    oCredential = CredentialCache.DefaultCredentials;
                }
                else
                {
                    oCredential = new NetworkCredential(textBoxUsername.Text, textBoxPassword.Text);
                    (oCredential as NetworkCredential).Domain = textBoxDomain.Text;
                }
                return oCredential;
            }
        }

        private void buttonEditHeaders_Click(object sender, EventArgs e)
        {
            FormHeaders oForm = new FormHeaders();
            _RequestHeaders=oForm.EditHeaders(_RequestHeaders,this);
            oForm.Dispose();
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string sWebDAVRequest = richTextBoxRequest.Text;

            richTextBoxResponse.Text = "";
            richTextBoxResponse.Refresh();
            buttonSend.Enabled = false;
            ClassWebDAV oWebDAV = new ClassWebDAV(textBoxWebdavURL.Text, CurrentCredentials, checkBoxBypassWebProxy.Checked,_logger);
            richTextBoxResponse.Text = oWebDAV.SendRequest(sWebDAVRequest,comboBoxMethod.Text,_RequestHeaders);
            buttonSend.Enabled = true;
        }

        private void checkBoxUseDefault_CheckedChanged(object sender, EventArgs e)
        {
            UpdateTextBoxState();
        }

        private void UpdateTextBoxState()
        {
            textBoxUsername.Enabled = !checkBoxUseDefault.Checked;
            textBoxPassword.Enabled = !checkBoxUseDefault.Checked;
            textBoxDomain.Enabled = !checkBoxUseDefault.Checked;
        }

        private void ReadSettingsFromRegistry()
        {
            string sRootKey = "Software\\" + Application.CompanyName + "\\" + Application.ProductName;
            Microsoft.Win32.RegistryKey oKey=Microsoft.Win32.Registry.CurrentUser.OpenSubKey(sRootKey,false);
            if (oKey == null) return;

            string sTemp=(string)oKey.GetValue("WebDAV URL", "");
            if (!string.IsNullOrEmpty(sTemp))
                textBoxWebdavURL.Text=sTemp;

            sTemp = (string)oKey.GetValue("BypassProxy", "True");
            if (!string.IsNullOrEmpty(sTemp))
                checkBoxBypassWebProxy.Checked = Convert.ToBoolean(sTemp);

            sTemp = (string)oKey.GetValue("Username", "");
            if (!string.IsNullOrEmpty(sTemp))
                textBoxUsername.Text=sTemp;

            sTemp=(string)oKey.GetValue("Password","");
            if (!string.IsNullOrEmpty(sTemp))
                textBoxPassword.Text=sTemp;

            sTemp=(string)oKey.GetValue("Domain","");
            if (!string.IsNullOrEmpty(sTemp))
                textBoxDomain.Text=sTemp;

            oKey.Close();
        }

        private void WriteSettingsToRegistry()
        {
            string sRootKey = "Software\\" + Application.CompanyName + "\\" + Application.ProductName;
            Microsoft.Win32.RegistryKey oKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(sRootKey, true);
            if (oKey == null)
            {
                // Key doesn't exist, so create it
                oKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(sRootKey, Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree);
                if (oKey == null)
                    return;
            }

            oKey.DeleteValue("WebDAV URL",false);
            oKey.SetValue("WebDAV URL", textBoxWebdavURL.Text);

            oKey.DeleteValue("BypassProxy", false);
            oKey.SetValue("BypassProxy", checkBoxBypassWebProxy.Checked);

            oKey.DeleteValue("Username", false);
            oKey.SetValue("Username", textBoxUsername.Text);

            oKey.DeleteValue("Password", false);
            oKey.SetValue("Password", textBoxPassword.Text);

            oKey.DeleteValue("Domain", false);
            oKey.SetValue("Domain", textBoxDomain.Text);

            oKey.Close();
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            WriteSettingsToRegistry();
        }

        private void buttonListener_Click(object sender, EventArgs e)
        {
            FormListener oForm = HTTPListener;
            if (!oForm.Visible)
                oForm.Show(this);
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            _logger = null;
            GC.Collect();
        }

    }
}
